package part2;

/**
 * @Author: shaochong
 * @Date: 2021/8/12
 * @Description:编写一个函数来查找字符串数组中的最长公共前缀。
 *
 * 如果不存在公共前缀，返回空字符串 ""。
 */
public class Solution14 {
    public static String longestCommonPrefix(String[] strs) {

        if (strs.length == 0) return  "";

        String s = strs[0];
        for (int i = 1; i < strs.length; i++) {
            s = getCommon(s, strs[i]);
            if ("".equals(s)) {
                return "";
            }
        }
        return s;
    }
    
    public static String getCommon(String s1, String s2) {
        int i = 0;
        for (i = 0; i<s1.length() && i<s2.length() ; i++) {
            System.out.println(s1.charAt(i) + " " + s2.charAt(i));
            if (s1.charAt(i) == s2.charAt(i)) {
                continue;
            } else {
                if (i==0) return "";
                return s1.substring(0, i);
            }
        }

        if (i == s1.length()) {
            return s1;
        }

        if (i == s2.length()) {
            return s2;
        }
        return "";
    }
    
    public static void main(String[] args) {
        String[] arr = {"dog123","dog156","dog122456"};
        System.out.println(longestCommonPrefix(arr));
    }
}
